package com.unice.miage.oobdoo.servlet;

import com.unice.miage.oobdoo.entity.Utilisateur;
import com.unice.miage.oobdoo.manager.AlbumManager;
import javax.ejb.EJB;
import javax.servlet.annotation.WebServlet;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javaxt.io.Image;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;

/**
 * Handles the multi-part MIME encoded POST from Plupload.
 *
 * @author Shad Aumann
 */
@WebServlet(name="PluploadServlet", urlPatterns={"/PluploadServlet"})
public class PluploadServlet extends HttpServlet {
    @EJB
    private AlbumManager albumManager;
	static private final long serialVersionUID = 3447685998419256747L;
	static private final String RESP_SUCCESS = "{\"jsonrpc\" : \"2.0\", \"result\" : null, \"id\" : \"id\"}";
	static private final String RESP_ERROR = "{\"jsonrpc\" : \"2.0\", \"error\" : {\"code\": 101, \"message\": \"Failed to open input stream.\"}, \"id\" : \"id\"}";
	static public final String SEP = System.getProperty("file.separator");
	static public final String JSON = "application/json";
	static public final int BUF_SIZE = 1024;


        private int idAlbum;
        private Utilisateur u;

	/**
	 * Handles an HTTP POST request from Plupload.
	 *
	 * @param req The HTTP request
	 * @param resp The HTTP response
	 */
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String responseString = RESP_SUCCESS;


                int id = Integer.valueOf(req.getParameter("IdAlbum"));
                this.idAlbum = id;
                this.u = albumManager.getAlbumById(this.idAlbum).getAuteur();
		boolean isMultipart = ServletFileUpload.isMultipartContent(req);

		if (isMultipart) {
			ServletFileUpload upload = new ServletFileUpload();

			try {
				FileItemIterator iter = upload.getItemIterator(req);
				while (iter.hasNext()) {
				    FileItemStream item = iter.next();
				    String name = item.getFieldName();
				    InputStream input = item.openStream();

				    // Handle a form field.
				    if (item.isFormField()) {
				        System.out.println("name=" + name + ", value=" + Streams.asString(input));
				    }

				    // Handle a multi-part MIME encoded file.
				    else {
				        saveUploadFile(input, item);
				    }
				}
			}
			catch (Exception e) {
				responseString = RESP_ERROR;
				e.printStackTrace();
			}
		}

		// Not a multi-part MIME request.
		else {
			responseString = RESP_ERROR;
		}

		resp.setContentType(JSON);
		byte[] responseBytes = responseString.getBytes();
		resp.setContentLength(responseBytes.length);
		ServletOutputStream output = resp.getOutputStream();
		output.write(responseBytes);
		output.flush();
                output.close();
	}

	/**
	 * Saves the given file item (using the given input stream) to the web server's
	 * local temp directory.
	 *
	 * @param input The input stream to read the file from
	 * @param item The multi-part MIME encoded file
	 */
	private void saveUploadFile(InputStream input, FileItemStream item) throws IOException {

                String path = this.getServletContext().getInitParameter("PATH");
                //String path =  System.getProperty("user.dir")+"/applications/oobdoo/web/";
		File localFile = new File(path+"upload/"+ u.getId()+"/"+ this.idAlbum +"/"+ item.getName());
		BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(localFile));
		byte[] data = new byte[BUF_SIZE];

		int count;
		while ((count = input.read(data, 0, BUF_SIZE)) != -1) {
			output.write(data, 0, count);
		}
               

		input.close();
		output.flush();
		output.close();

                // GENERATION DES THUMBS
                int mid= item.getName().lastIndexOf(".");
                String fname=item.getName().substring(0,mid);
                String ext=item.getName().substring(mid+1,item.getName().length());

                // THUMB 140* - PAGE D'UN ALBUM
                Image image = new Image(path+"upload/"+ u.getId()+"/"+ this.idAlbum +"/"+ item.getName());
                image.setWidth(140); //set width, adjusts height to maintain aspect ratio

                image.saveAs(path+"upload/"+ u.getId()+"/"+ this.idAlbum +"/"+ fname+"_thumb_140."+ext);

                // THUMB 500* - PAGE D'UNE PHOTO
                Image image2 = new Image(path+"upload/"+ u.getId()+"/"+ this.idAlbum +"/"+ item.getName());
                image2.setWidth(500); //set width, adjusts height to maintain aspect ratio

                image2.saveAs(path+"upload/"+ u.getId()+"/"+ this.idAlbum +"/"+ fname+"_thumb_500."+ext);

                // THUMB 224*220 PAGE ACCUEIL
                Image image3 = new Image(path+"upload/"+ u.getId()+"/"+ this.idAlbum +"/"+ item.getName());
                image3.setWidth(225);
                if(image3.getHeight() < 220)
                {
                    image3.setHeight(221);
                }
                
                int x = (image3.getWidth()/2)-(224/2);
                int y = (image3.getHeight()/2)-(220/2);
                
                image3.crop(x,y,224,220);
                image3.saveAs(path+"upload/"+ u.getId()+"/"+ this.idAlbum +"/"+ fname+"_thumb_224."+ext);
	}
}